package com.hezhi.framework.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {   
    protected final transient Log log = LogFactory.getLog(getClass());   
      
    /**
     * 
     * @param source
     * @param out
     * @param dwidth
     * @param dheight
     * @throws Exception
     */
    public static void outLogo(byte[] source,OutputStream out,int dwidth,int dheight) throws Exception{   
        BufferedInputStream stream = new BufferedInputStream((new ByteArrayInputStream(source)),8092);//控制流速   
        Image src = javax.imageio.ImageIO.read(stream);   
        int width=src.getWidth(null);   
        int height=src.getHeight(null);   
        int towidth,toheight;   
        if (width>dwidth || height>dheight){   
            if (((float)width/dwidth)>=((float)height/dheight)){   
                towidth = dwidth;   
                toheight = (height*dwidth)/width;   
            }else{   
                toheight = dheight;   
                towidth = (width* dheight)/height;   
            }   
        }else{   
            towidth= width;   
            toheight=height;   
        }   
           
        BufferedImage tag = new BufferedImage(towidth,toheight,BufferedImage.TYPE_INT_RGB);   
        tag.getGraphics().drawImage(src,0,0,towidth,toheight,null);   
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
        encoder.encode(tag);   
    }   
} 
